package cn.fancy.sdk.service;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import cn.fancy.sdk.common.utils.ResUtil;

import cn.fancy.sdk.service.utils.QdJSLinker;
import cn.fancy.sdk.service.utils.QdMakeLog;

public class QdWebview extends Activity implements OnClickListener {
    
    private static String TAG = QdWebview.class.getSimpleName();
    private static String homePage;
    private static boolean multiplePages;
    
    private ImageView closeBtn;
    private ImageView backBtn;
    private ImageView forwardBtn;
    private ImageView reloadBtn;
    private Dialog dialog;
    private WebView webView;
    private LinearLayout webError;
    private Timer mTimer;
    
    static void start(Context context, String url) {
        homePage = url;
        multiplePages = false;
        String uid = QdUserInfo.output(QdUserInfo.PARAMS_USERID);
        
        if (uid.equals("")) {
            QdMakeLog.e(TAG, "uid is empty, check it out and try again");
            Toast.makeText(context, "功能暂未开放，敬请期待", Toast.LENGTH_SHORT).show();
            return;
        }
        
        QdMakeLog.d(TAG, "start");
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setClass(context, QdWebview.class);
        context.startActivity(intent);
    }
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(ResUtil.getLayoutId(QdWebview.this, "fancy_webview_service"));
        overridePendingTransition(
            ResUtil.getAnimId(QdWebview.this, "qdservice_in_from_right"),
            ResUtil.getAnimId(QdWebview.this, "qdservice_out_to_right"));
        
        mTimer = new Timer();
        dialog = USLodeDialog.showWaitingDialog(QdWebview.this,
            new OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    QdWebview.this.finish();
                }
            });
        
        closeBtn = (ImageView) this.findViewById(ResUtil.getId(QdWebview.this,
            "fancyservice_btn_close"));
        closeBtn.setOnClickListener(this);
        
        backBtn = (ImageView) this.findViewById(ResUtil.getId(QdWebview.this,
            "fancyservice_btn_back"));
        backBtn.setOnClickListener(this);
        
        forwardBtn = (ImageView) this.findViewById(ResUtil.getId(QdWebview.this,
            "qdservice_btn_forward"));
        forwardBtn.setOnClickListener(this);
        
        reloadBtn = (ImageView) this.findViewById(ResUtil.getId(QdWebview.this,
            "qdservice_btn_reload"));
        reloadBtn.setOnClickListener(this);
        
        if (multiplePages == false) {
            backBtn.setBackground(this.getResources().getDrawable(
                ResUtil.getDrawableId(this, "qdservice_backward_gray")));
            backBtn.setClickable(false);
            forwardBtn.setBackground(this.getResources().getDrawable(
                ResUtil.getDrawableId(this, "qdservice_forward_gray")));
            forwardBtn.setClickable(false);
        }
        
        webError = (LinearLayout) this.findViewById(ResUtil.getId(
            QdWebview.this, "qdservice_webview_error"));
        webError.setVisibility(View.GONE);
        
        webView = (WebView) this.findViewById(ResUtil.getId(QdWebview.this,
            "qdservice_webview_page"));
        setWebview();
        webView.loadUrl(homePage);
    }
    
    /* webView配置 */
    private void setWebview() {
        webView.setFocusable(true);
        webView.setFocusableInTouchMode(true);
        webView.getSettings().setSupportZoom(false);
        webView.getSettings().setAllowFileAccess(true);
        webView.getSettings().setDatabaseEnabled(false);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setAppCacheEnabled(false);
        webView.getSettings().setDomStorageEnabled(false);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setDefaultTextEncodingName("UTF-8");
        webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        
        webView.addJavascriptInterface(new QdJSLinker(this), "ClientService");
        
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
				if (dialog.isShowing()) {
					dialog.show();
				}
                webError.setVisibility(View.GONE);
            }
            
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
            
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
				if (dialog.isShowing()) {
					dialog.hide();
				}
            }
            
            @Override
            public void onReceivedError(WebView view, int errorCode,
                String description, String failingUrl) {
                QdMakeLog.d(TAG, "load error");
                webError.setVisibility(View.VISIBLE);
            }
        });
        
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(final WebView view, int progress) {
                super.onProgressChanged(view, progress);
                if (progress > 80) {
                    long delay = 500;
                    if (progress < 90) {
                        delay = delay + (90 - progress) * 100;
                    }
                    mTimer.cancel();
                    mTimer = new Timer();
                    TimerTask task = new TimerTask() {
                        public void run() {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    QdMakeLog.d(TAG,
                                        "stop loading dialog on timer");
									if (dialog.isShowing()) {
										dialog.hide();
									}
                                }
                            });
                        }
                    };
                    mTimer.schedule(task, delay);
                }
            }
        });
        
    }
    
    @Override
    public void onBackPressed() {
        this.finish();
        mTimer.cancel();
		if (dialog != null) {
			dialog.dismiss();
		}
        QdMakeLog.d(TAG, "closed");
    }
    
    @Override
    public void onStop() {
        super.onStop();
    }
    
    @Override
    public void onClick(View v) {
        if (v.getId() == ResUtil.getId(QdWebview.this, "fancyservice_btn_close")) {
            webView.clearHistory();
            this.onBackPressed();
        } else if (v.getId() == ResUtil.getId(QdWebview.this,
            "fancyservice_btn_back")) {
			if (webView.canGoBack()) {
				webView.goBack();
			}
        } else if (v.getId() == ResUtil.getId(QdWebview.this,
            "qdservice_btn_forward")) {
			if (webView.canGoForward()) {
				webView.goForward();
			}
        } else if (v.getId() == ResUtil.getId(QdWebview.this,
            "qdservice_btn_reload")) {
            webView.reload();
        }
    }
    
    @Override
    protected void onResume() {
        super.onResume();
    }
}
